package com.nami.framework.security.handler;

import com.nami.common.constants.SystemConstants;
import com.nami.common.response.R;
import com.nami.common.response.ResponseCodeEnum;
import com.nami.common.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Security 未登录处理 Handler
 *
 * @author C
 */
@Slf4j
@Component
public class SecureityAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        log.warn("未知账户");
        // 判断url是不是为空,如果为空去登录页面
        String uri = request.getRequestURI();
        log.info("uri: {}", uri);
        if (SystemConstants.SLASH.equals(uri)) {
            response.sendRedirect("/index");
        } else if ("/index".equals(uri)) {
            response.sendRedirect("/login");
        } else {
            R<Void> result = R.failed(ResponseCodeEnum.FAILED_401.getCode(), ResponseCodeEnum.FAILED_401.getMessage());
            ServletUtils.writeJson(result);
        }
    }
}
